#ifndef __COMM_HPP__
#define __COMM_HPP__
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include "log.hpp"

using namespace std;

const string pathName = "/home/yzh";
const int projectId = 0x6666;
Log log;

key_t getKey(){
    key_t key = ftok(pathName.c_str(), projectId);
    if(key == -1){
        log(Fatal, "pid : %d, position : [%s, line : %d], ftok error : %s", getpid(), __FILE__, __LINE__, strerror(errno));
        exit(1);
    }
    log(Info, "pid : %d, position : [%s, line : %d], get key success : %d", getpid(), __FILE__, __LINE__, key);
    return key;
}

int ShareMemHelper(int flag){ 
    key_t key = getKey(); // 获取key
    int shmid = shmget(key, 4096, flag);  // 获取共享内存
    if(shmid == -1){
        log(Fatal, "pid : %d, position : [%s, line : %d], shmget error : %s", getpid(), __FILE__, __LINE__, strerror(errno));
        exit(2);
    }
    log(Info, "pid : %d, position : [%s, line : %d], get share memory success : %d", getpid(), __FILE__, __LINE__, shmid);
    return shmid;
} 

int createShareMem(){
    return ShareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}

int getShareMem(){
    return ShareMemHelper(IPC_CREAT);
}



#endif